package com.hans.scala.collection

/**
 * list 高阶方法
 * Created by Hans on 2014/4/8.
 */
object HigherOrderMethodExample {
  def main(args: Array[String]) {
    val words = List("the", "quick", "brown", "fox")
    println(words.map(_.length))
    println(words.map(str => str.length))
    println(words.map((str: String) => str.length))

    //filter
    List.range(1, 7).filter(_ % 2 == 0)

    //partition
    List.range(1, 7).partition(_ % 2 == 0)._1

    //列表的论断 forall exists
    def hasZeroRow(m: List[List[Int]]) = m.exists(row => row forall (_ == 0))
    val listList = List(List(1, 4, 5), List(0, 0, 0), List(2, 3, 6))
    println(hasZeroRow(listList))

    //折叠列表
    def sum(xs: List[Int]): Int = (0 /: xs)(_ + _)
    sum(List(1, 5, 7))
    def product(xs: List[Int]): Int = (2 /: xs)(_ * _)
    product(List(1, 5, 7))
    ("#" /: words.tail)(_ + " " + _)
    (words.tail :\ "#")(_ + " " + _)
    (List[Int]() /: List(5, 7, 1, 3))((ys, y) => y :: ys)//利用左折叠 倒序
    //用折叠可以获得当前参数与前或后参数
    def flatTenLeft[T](xss: List[List[T]]) = (List[T]() /: xss)(_ ::: _)
    def flatTenRight[T](xss: List[List[T]]) = (xss :\ List[T]())(_ ::: _)
    println(flatTenRight(List(List("a", "b"), List("c", "d"))))
    println(flatTenLeft(List(List("a", "b"), List("c", "d"))))

    //连接
    List(List('c', 'a'), List('b')).flatten //内部方法 1个参数
    List.concat(List('c', 'a'), List('a')) //外部方法 n个参数

    //map2
//    List.map2(List(10, 20), List(2, 3))(_ * _)
//    (List(10, 20), List(2, 3)).zipped.map(_ * _)
//    //forall2
//    List.forall2(List("abc", "de"), List(3, 2))((x: String, y: Int) => x.length == y)
//    List.forall2(List("abc", "de"), List(3, 2))(_.length == _)
    (List("abc", "de"), List(3, 2)).zipped.forall(_.length == _)
    //exists
    (List("abc", "de"), List(3, 2)).zipped.exists(_.length == _)

  }
}
